package com.cloud.xtools.user.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.xtools.common.exception.ServiceException;
import com.cloud.xtools.common.redis.RedisService;
import com.cloud.xtools.common.response.PageList;
import com.cloud.xtools.common.util.Dump;
import com.cloud.xtools.common.util.XPage;
import com.cloud.xtools.user.domain.entity.User;
import com.cloud.xtools.user.domain.request.admin.UserCreateRequest;
import com.cloud.xtools.user.domain.query.admin.UserQuery;
import com.cloud.xtools.user.domain.request.admin.UserUpdateRequest;
import com.cloud.xtools.user.domain.resource.admin.UserResource;
import com.cloud.xtools.user.mapper.UserMapper;
import com.cloud.xtools.user.service.admin.RoleService;
import com.cloud.xtools.user.service.admin.UserRoleService;
import com.cloud.xtools.user.service.admin.UserService;
import com.cloud.xtools.common.util.Auth;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Daixinguo
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    // 自动装配 BCryptPasswordEncoder
    private final PasswordEncoder passwordEncoder;

    private final RoleService roleService;

    private final UserRoleService userRoleService;
    private final RedisService redisService;

    @Override
    public PageList list(UserQuery userQuery) {
        // QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> queryWrapper = Wrappers.query();
        // userQuery.getUsername() != null && !userQuery.getUsername().isEmpty()
        if (!StrUtil.hasBlank(userQuery.getUsername())) {
            queryWrapper.like("username", userQuery.getUsername());
        }
        if (!StrUtil.hasBlank(userQuery.getName())) {
            queryWrapper.like("name", userQuery.getName());
        }
        if (!StrUtil.hasBlank(userQuery.getMobile())) {
            queryWrapper.like("mobile", userQuery.getMobile());
        }
        if (!StrUtil.hasBlank(userQuery.getEmail())) {
            queryWrapper.like("email", userQuery.getEmail());
        }
        if (userQuery.getAdmin() != null) {
            queryWrapper.eq("admin", userQuery.getAdmin());
        }

        // 创建 Page 对象
        // IPage<User> page = new Page<>(userQuery.getPageNum(), userQuery.getPageSize());
        // IPage<User> users = userMapper.selectPage(page, queryWrapper);

        // 分页，由于需要关联查询用户的角色，所以需要自定义查询
        // int offset = (userQuery.getPageNumber() - 1) * userQuery.getPageSize();
        // queryWrapper.last("LIMIT " + userQuery.getPageSize() + " OFFSET " + offset);

        // 开启分页
        // PageHelper.startPage(userQuery.getPageNum(), userQuery.getPageSize());
        XPage.startPage(userQuery.getPageNum(), userQuery.getPageSize());

        List<User> users = userMapper.userList(queryWrapper);

        // 封装分页信息
        // PageInfo<UserResource> pageInfo = new PageInfo<>(BeanUtil.copyToList(userMapper.userList(queryWrapper),UserResource.class));
        // Dump.json(pageInfo);

        // final var pageList = XPage.page(users, UserResource.class);
        // System.out.println(pageList);

        return XPage.page(users, UserResource.class);
    }

    @Override
    public UserResource add(UserCreateRequest userCreateRequest) {
        // 明文密码加密
        userCreateRequest.setPassword(passwordEncoder.encode(userCreateRequest.getPassword()));
        User user = BeanUtil.copyProperties(userCreateRequest, User.class);
        save(user);
        return BeanUtil.copyProperties(user, UserResource.class);
    }

    @Override
    public void edit(Long id, UserUpdateRequest userUpdateRequest) {
        userUpdateRequest.setId(id);
        if (!StrUtil.hasBlank(userUpdateRequest.getPassword()) ) {
            // 明文密码加密
            userUpdateRequest.setPassword(passwordEncoder.encode(userUpdateRequest.getPassword()));
        }
        User user = BeanUtil.copyProperties(userUpdateRequest, User.class);
        try {
            updateById(user);
        } catch (Exception e) {
            throw new ServiceException("更新失败");
        }
    }

    @Override
    public void destroy(Long id) {
        try {
            // 删除用户角色关联数据
            userRoleService.destroyByUserId(id);
            removeById(id);
        } catch (Exception e) {
            throw new ServiceException("删除失败");
        }
    }

    @Override
    public void assignRole(Long id, List<Long> roleIds) {

        // 检查 roleIds 是否均存在
        if (roleService.countByIds(roleIds) != roleIds.size()){
            throw new ServiceException("分配中有不存在的角色，请检查");
        }
        userRoleService.assignRoles(id, roleIds);
    }

    @Override
    public UserResource userInfo() {
        User user = getById(Auth.getUserId());
        return BeanUtil.copyProperties(user, UserResource.class);
    }

    @Override
    public UserResource userInfoById(Long id) {
        User user = getById(id);
        return BeanUtil.copyProperties(user, UserResource.class);
    }

    // 获取当前登录用户所拥有的权限
    // @Override
    // public Set<Object> getUserPermissions() {
    //     String roleKey = "user_role:" + Auth.getUserId();
    //     Set<Object> roleIds = redisService.getSet(roleKey);
    //     Set<Object> allPermissions = new HashSet<>();
    //     roleIds.forEach(roleId -> {
    //         String permissionKey = "role_permission:" + roleId;
    //         allPermissions.addAll(redisService.getSet(permissionKey));
    //     });
    //     // System.out.println("#####");
    //     // System.out.println(allPermissions);
    //     return allPermissions;
    // }
}
